package com.cdks.wuxiu.api.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.extra.servlet.ServletUtil;

import com.cdks.wuxiu.api.model.common.CommonHeader;
import com.cdks.wuxiu.common.component.constant.ApiCodeEnum;
import com.cdks.wuxiu.common.exception.ApiException;
import com.cdks.wuxiu.common.util.ServletUtils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Security 工具类
 */
@Slf4j
@Component
public class AuthUtils {
    /**
     * 加密
     */
    private static String encrypt(long userId, long nonce, String src) {
        return SecureUtil.md5(userId + "&" + src + "&" + nonce);
    }

    /**
     * 获取请求公共 Header 参数
     */
    public static CommonHeader getCommonHeader() {
        HttpServletRequest request = ServletUtils.getRequest();
        Map<String, String> headerMap = ServletUtil.getHeaderMap(request);
        
        try {
            return BeanUtil.toBean(headerMap, CommonHeader.class);
        } catch (Exception e) {
            log.error("转换Header参数异常", e);
            throw new ApiException(ApiCodeEnum.PARAM_ERROR);
        }
    }

    /**
     * 计算请求参数签名
     */
    public static String signParam(Object param) {
        Map<String, Object> paramMap = BeanUtil.beanToMap(param);
        String sortStr  = MapUtil.sortJoin(paramMap, "&", "=", true);
        String sign     = SecureUtil.md5(sortStr + "20");

        log.info("参数签名：" + sortStr + " => " + sign);
        
        return sign;
    }

    /**
     * token加密
     */
    public static String encryptToken(long userId, long nonce, String token) {
        return encrypt(userId, nonce, token);
    }

    /**
     * 挑战码加密
     */
    public static String encryptChalln(long userId, long nonce, String challn) {
        return encrypt(userId, nonce, challn);
    }
}
